package org.jflame.captcha;

import org.jflame.commons.file.FileFilters.SuffixFileFilter;
import org.jflame.commons.util.ArrayHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.Validate;

public class RandomImgManager {

    private List<Path> imgListing;

    /**
     * 构造函数
     * 
     * @param images 供选择的图片路径
     */
    public RandomImgManager(List<Path> images) {
        imgListing = Validate.notEmpty(images, "images must not be null");
    }

    /**
     * 构造函数
     * 
     * @param imageFolder 图片所在目录,该目录下所有图片文件供选择
     */
    public RandomImgManager(final String imageFolder) throws IOException {
        this(imageFolder, 0);
    }

    /**
     * 构造函数
     * 
     * @param imageFolder 背景图片所在目录,读取该目录下图片文件作为供选择的背景图
     * @param maxFiles 最大文件个数,0表示不限制
     */
    public RandomImgManager(final String imageFolder, final int maxFiles) throws IOException {
        Objects.requireNonNull(imageFolder, "imageFolder must not be null");
        File bgDir = new File(imageFolder);
        if (!bgDir.exists()) {
            throw new FileNotFoundException("目录不存在:" + imageFolder);
        }

        filterImage(imageFolder, maxFiles, bgDir);
    }

    final String[] imgExt = { "jpg","jpeg","png","bmp","gif" };

    private void filterImage(final String imageFolder, final int maxFiles, File bgDir) throws FileNotFoundException {
        File[] bgFiles = bgDir.listFiles(new SuffixFileFilter(imgExt));
        if (ArrayHelper.isEmpty(bgFiles)) {
            throw new FileNotFoundException("目录下没有符合条件的文件:" + imageFolder);
        }
        int endIndex = maxFiles <= 0 || maxFiles >= bgFiles.length ? bgFiles.length : maxFiles;
        imgListing = new ArrayList<>(endIndex);
        for (int i = 0; i < maxFiles; i++) {
            imgListing.add(bgFiles[i].toPath());
        }
    }

    /**
     * 随机返回一个文件
     * 
     * @return
     * @throws IOException
     */
    public File nextFile() throws IOException {
        Path selectFileName = imgListing.get(RandomUtils.nextInt(0, imgListing.size()));
        return selectFileName.toFile();
    }

    public List<Path> getBgImgs() {
        return imgListing;
    }

}
